import React, { PureComponent } from 'react';
import { Avatar,Tooltip } from 'antd';



export default class AvatarCustom extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      imageStatus: false,
    };
  }

  handleImageLoaded() {
    this.setState({ imageStatus: true });
  }

  handleImageErrored() {
    this.setState({ imageStatus: false });
  }

  stringToHex(str){
    let val=0, n=0;
    if(str){
      val = str.charCodeAt(0);
    }
    str="" ? n=0 : n=val % 10;
    return n;
  }

  render() {
    const { src, letters, style, index, tooltip, ...restProps } = this.props;
    const { imageStatus } = this.state;

    const colorList = ['#f56a00', '#7265e6', '#ffbf00', '#00a2ae', '#1d70ee', '#483bcc', '#e02521', '#22245a', '#6d5b69', '#f99c00' ];


    // let get_color;
    // if(index!=null || index!=undefined){
    //    get_color=colorList[index % 10];
    // }else{
    //    get_color=colorList[Math.floor(Math.random()*10)];
    // }


    return (
      <span>
        <img
          src={src}
          onLoad={this.handleImageLoaded.bind(this)}
          onError={this.handleImageErrored.bind(this)}
          style={{display:'none'}}
        />
        { tooltip  && (
          <Tooltip  placement="bottom" title={letters}>
            {
              (src && imageStatus) ?
                <Avatar {...restProps} src={src} style={style} /> :
                <Avatar {...restProps} style={{backgroundColor:colorList[this.stringToHex(letters)], cursor: 'pointer',color:'#fff',...style}}>{letters ? [...letters.toUpperCase()][0] : 'U'}</Avatar>
            }
          </Tooltip>

        )}

        { !tooltip && (

              (src && imageStatus ) ?
                <Avatar {...restProps} src={src} style={style} /> :
                <Avatar {...restProps} style={{backgroundColor:colorList[this.stringToHex(letters)], cursor: 'pointer',color:'#fff',...style}}>{letters ? [...letters.toUpperCase()][0] : 'U'}</Avatar>

        )}

      </span>





    );
  }



};
